<template>
  <div class="main h-[calc(100%-29px)]">
    <div class="w-full">
      <div v-if="queryShow" class="mb-[10px] w-full search-form">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.blurry"
              clearable
              placeholder="模糊搜索"
            />
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryForm.data.createTime"
              type="datetimerange"
              range-separator=":"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >搜索</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="w-full">
        <div class="w-full flex justify-between">
          <div class="buttons flex align-center">
            <el-button type="primary" :icon="Plus" @click="addMenu"
              >新增</el-button
            >
            <el-button
              type="success"
              :icon="Edit"
              :disabled="!(multipleSelection.length === 1)"
              @click="editSelect"
              >修改</el-button
            >
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="!multipleSelection.length"
              @click="delSelect"
              >删除</el-button
            >
            <el-button type="warning" :icon="Download" @click="exportData"
              >导出</el-button
            >
          </div>
          <div class="settings">
            <el-button-group class="ml-4">
              <el-button
                type="primary"
                :icon="Search"
                @click="queryShow = !queryShow"
              />
              <el-button type="primary" :icon="RefreshLeft" @click="getList" />
              <el-popover placement="bottom" :width="200" trigger="click">
                <template #reference>
                  <el-button type="primary" :icon="Grid" />
                </template>
                <el-checkbox
                  v-model="checkAll"
                  :indeterminate="isIndeterminate"
                  @change="handleCheckAllChange"
                  >全选</el-checkbox
                >
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-popover>
            </el-button-group>
          </div>
        </div>
        <div class="flex">
          <div class="role w-full">
            <div v-loading="loading" class="w-full mt-[10px]">
              <el-table
                :key="tableKey"
                ref="multipleTableRef"
                :data="tableData.data"
                style="width: 100%"
                row-key="id"
                lazy
                :load="load"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren'
                }"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column
                  v-for="item in colums.data"
                  :key="item.prop"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width"
                >
                  <template
                    v-if="
                      ['iFrame', 'cache', 'hidden', 'icon'].indexOf(
                        item.prop
                      ) >= 0
                    "
                    #default="scope"
                  >
                    <span
                      v-if="item.prop === 'iFrame' || item.prop === 'cache'"
                      >{{ scope.row[item.prop] ? "是" : "否" }}</span
                    >
                    <span v-if="item.prop === 'hidden'">{{
                      scope.row[item.prop] ? "否" : "是"
                    }}</span>
                    <component
                      :is="
                        useRenderIcon(
                          toRaw(scope.row.icon) ||
                            (scope.row.icon && toRaw(scope.row.icon))
                        )
                      "
                      v-if="item.prop === 'icon'"
                    />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      :icon="Edit"
                      @click="editRow(scope.row)"
                    />
                    <el-popconfirm
                      width="200px"
                      title="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
                      @confirm="delConfirm(scope.row)"
                    >
                      <template #reference>
                        <el-button type="danger" size="small" :icon="Delete" />
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addDialog"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :title="title"
      width="580px"
    >
      <el-form
        ref="formRef"
        :model="form.data"
        :rules="form.rules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.data.type" size="mini">
                <el-radio-button label="0">目录</el-radio-button>
                <el-radio-button label="1">菜单</el-radio-button>
                <el-radio-button label="2">按钮</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="form.data.type.toString() !== '2'" :span="24">
            <el-form-item label="菜单图标" prop="icon">
              <IconSelect
                :key="Math.random()"
                v-model="form.data.icon"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col v-show="form.data.type.toString() !== '2'" :span="12">
            <el-form-item label="外链菜单" prop="iFrame">
              <el-radio-group v-model="form.data.iFrame" size="mini">
                <el-radio-button label="true">是</el-radio-button>
                <el-radio-button label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="form.data.type.toString() !== '2'" :span="12">
            <el-form-item label="菜单可见" prop="hidden">
              <el-radio-group v-model="form.data.hidden" size="mini">
                <el-radio-button label="false">是</el-radio-button>
                <el-radio-button label="true">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="form.data.type.toString() === '1'" :span="12">
            <el-form-item label="菜单缓存" prop="cache">
              <el-radio-group v-model="form.data.cache" size="mini">
                <el-radio-button label="true">是</el-radio-button>
                <el-radio-button label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.data.type.toString() !== '2'" :span="24">
            <el-form-item label="菜单标题" prop="title">
              <el-input v-model="form.data.title" placeholder="菜单标题" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.data.type.toString() !== '2'" :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.data.path" placeholder="路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单排序" prop="menuSort">
              <el-input-number
                v-model.number="form.data.menuSort"
                :min="0"
                :max="999"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.data.type.toString() === '2'" :span="12">
            <el-form-item label="按钮名称" prop="title">
              <el-input v-model="form.data.title" placeholder="按钮名称" />
            </el-form-item>
          </el-col>
          <el-col v-show="form.data.type.toString() !== '0'" :span="12">
            <el-form-item label="权限标识" prop="permission">
              <el-input
                v-model="form.data.permission"
                :disabled="form.data.iFrame.toString() === 'true'"
                placeholder="权限标识"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-show="
              form.data.iFrame.toString() !== 'true' &&
              form.data.type.toString() === '1'
            "
            :span="12"
          >
            <el-form-item label="组件名称" prop="componentName">
              <el-input
                v-model="form.data.componentName"
                placeholder="匹配组件内Name字段"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-show="
              form.data.iFrame.toString() !== 'true' &&
              form.data.type.toString() === '1'
            "
            :span="12"
          >
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.data.component" placeholder="组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级类目" prop="pid">
              <el-tree-select
                v-model="form.data.pid"
                check-strictly
                :expand-on-click-node="false"
                :data="menusDataFormInner.data"
                nodeKey="id"
                lazy
                :load="loadNode"
                :props="propsMenu"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  Check,
  Delete,
  Download,
  Edit,
  Grid,
  Plus,
  RefreshLeft,
  Search
} from "@element-plus/icons-vue";
import {
  ElForm,
  ElMessageBox,
  ElNotification,
  ElTable,
  ElTree
} from "element-plus";
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  getCurrentLevel,
  getMenuList,
  getMenuListLazy,
  ResultRole,
  addMenuApi,
  getSuperior,
  editMenuApi,
  delMenuApi,
  ResultMenu,
  exportMenuList
} from "@/api/system";
import { IconSelect } from "@/components/ReIcon";
import Node from "element-plus/es/components/tree/src/model/node";
import { cloneDeep } from "@pureadmin/utils";
import { downloadFile } from "@/utils";
const queryShow = ref(true);
const queryForm = reactive({
  data: {
    blurry: undefined,
    createTime: []
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined,
    createTime: []
  };
};
const exportData = async () => {
  let res = await exportMenuList({
    page: 0,
    size: 10,
    sort: "id,desc",
    blurry: queryForm.data.blurry ? queryForm.data.blurry : undefined,
    createTime: queryForm.data.createTime.length
      ? queryForm.data.createTime
      : undefined
  });
  downloadFile(res, "菜单数据", "xlsx");
};
const tableKey = ref("table");
const search = async () => {
  let { content } = await getList();
  tableData.data = content;
  tableKey.value = "table" + Math.random();
};
const getList = () => {
  loading.value = true;
  return new Promise<ResultMenu>(async (resolve, reject) => {
    let data = await getMenuList({
      page: 0,
      size: 1000,
      sort: "id,desc",
      blurry: queryForm.data.blurry ? queryForm.data.blurry : undefined,
      createTime: queryForm.data.createTime.length
        ? queryForm.data.createTime
        : undefined
    });
    loading.value = false;
    resolve(data);
  });
};
const lazyGetList = pid => {
  loading.value = true;
  return new Promise<ResultRole>(async (resolve, reject) => {
    let data = await getMenuList({
      pid: pid
    });
    loading.value = false;
    resolve(data);
  });
};
const currentLevel = ref(3);
const init = async () => {
  const { level } = await getCurrentLevel();
  currentLevel.value = level;
};
init();
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "菜单标题",
      prop: "title"
    },
    {
      label: "图标",
      prop: "icon"
    },
    {
      label: "排序",
      prop: "menuSort"
    },
    {
      label: "权限标识",
      prop: "permission"
    },
    {
      label: "组件路径",
      prop: "component"
    },
    {
      label: "外链",
      prop: "iFrame"
    },
    {
      label: "缓存",
      prop: "cache"
    },
    {
      label: "可见",
      prop: "hidden"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "菜单标题",
      prop: "title"
    },
    {
      label: "图标",
      prop: "icon"
    },
    {
      label: "排序",
      prop: "menuSort"
    },
    {
      label: "权限标识",
      prop: "permission"
    },
    {
      label: "组件路径",
      prop: "component"
    },
    {
      label: "外链",
      prop: "iFrame"
    },
    {
      label: "缓存",
      prop: "cache"
    },
    {
      label: "可见",
      prop: "hidden"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const load = async (row, treeNode, resolve) => {
  let { content } = await lazyGetList(row.id);
  return resolve(content);
};
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  search();
  checkedCities.value = colums.data.map(item => item.prop);
});
const propsMenu = {
  label: "label",
  hasChildren: "hasChildren",
  children: "children",
  isLeaf: "leaf"
};
const form = reactive({
  data: {
    id: null,
    title: null,
    menuSort: 999,
    path: null,
    component: null,
    componentName: null,
    iFrame: false,
    roles: [],
    pid: 0,
    icon: "",
    cache: false,
    hidden: false,
    type: 0,
    permission: null
  },
  rules: {
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    path: [{ required: true, message: "请输入地址", trigger: "blur" }]
  }
});
const menusDataFormInner = reactive({
  data: []
});
const addDialog = ref(false);
const title = ref("新增菜单");
const status = ref("add");
const addMenu = () => {
  addDialog.value = true;
  title.value = "新增菜单";
  status.value = "add";
  menusDataFormInner.data = [];
  menusDataFormInner.data.push({ id: 0, label: "顶级类目", children: null });
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const editRow = row => {
  addDialog.value = true;
  title.value = "编辑菜单";
  status.value = "edit";
  menusDataFormInner.data = [];
  let data = cloneDeep(row);
  form.data = data;
  if (form.data.id) {
    if (!form.data.pid) {
      form.data.pid = 0;
    }
  }
  if (form.data.icon.indexOf(":") === -1) {
    form.data.icon = "ri:" + form.data.icon;
  }
  getSuperior([row.id]).then(res => {
    const children = res.map(function (obj) {
      if (!obj.leaf && !obj.children) {
        obj.children = null;
      }
      return obj;
    });
    menusDataFormInner.data = [
      { id: 0, label: "顶级类目", children: children }
    ];
  });
};
const delSelect = () => {
  if (multipleSelection.value.length) {
    ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}条数据?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(async () => {
      await delMenuApi(multipleSelection.value.map(i => i.id));
      ElNotification({
        title: "系统提示",
        message: "删除成功",
        type: "success"
      });
      search();
    });
  }
};
const editSelect = () => {
  if (multipleSelection.value.length === 1) {
    editRow(multipleSelection.value[0]);
  }
};
const formRef = ref<InstanceType<typeof ElForm>>();
const resetForm = () => {
  form.data = {
    id: null,
    title: null,
    menuSort: 999,
    path: null,
    component: null,
    componentName: null,
    iFrame: false,
    roles: [],
    pid: 0,
    icon: "",
    cache: false,
    hidden: false,
    type: 0,
    permission: null
  };
  nextTick(() => {
    formRef.value.resetFields();
  });
};
const beforeClose = d => {
  form.data = {
    id: null,
    title: null,
    menuSort: 999,
    path: null,
    component: null,
    componentName: null,
    iFrame: false,
    roles: [],
    pid: 0,
    icon: "",
    cache: false,
    hidden: false,
    type: 0,
    permission: null
  };
  nextTick(() => {
    d();
  });
};
const cancel = () => {
  form.data = {
    id: null,
    title: null,
    menuSort: 999,
    path: null,
    component: null,
    componentName: null,
    iFrame: false,
    roles: [],
    pid: 0,
    icon: "",
    cache: false,
    hidden: false,
    type: 0,
    permission: null
  };
  formRef.value.resetFields();
  nextTick(() => {
    addDialog.value = false;
  });
};
const submit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data = cloneDeep(form.data);
      if (status.value === "add") {
        await addMenuApi(data);
        ElNotification({
          title: "系统提示",
          message: "菜单创建成功",
          type: "success"
        });
      } else {
        await editMenuApi(data);
        ElNotification({
          title: "系统提示",
          message: "菜单编辑成功",
          type: "success"
        });
      }
      resetForm();
      nextTick(() => {
        addDialog.value = false;
        search();
      });
    }
  });
};
const delConfirm = async row => {
  await delMenuApi([row.id]);
  ElNotification({
    title: "系统提示",
    message: "删除成功",
    type: "success"
  });
  search();
};
const loadNode = async (node: Node, resolve: any) => {
  let id = "";
  if (!node.data.id) {
    if (node.data.id === 0) {
      id = "0";
    }
  } else {
    id = node.data.id;
  }
  if (!id) {
    return resolve([{ id: 0, label: "顶级类目" }]);
  } else {
    let data = await getMenuListLazy({ pid: id });
    return resolve(data);
  }
};
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  //margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}
</style>
